package com.nd.mobile.study.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;

import com.nd.mobile.study.common.config.Config;
import com.nd.mobile.study.common.constants.Tips;
import com.nd.mobile.study.common.exception.LocalErrorException;
import com.nd.mobile.study.common.exception.LogicException;

public class HttpRequestUtil {
	
	public static String TAG = "HttpRequestUtil";
	private static int	timeoutConnection	= 7000;
	private static int	timeoutSocket		= 10000;

	public static String get(String command, Bundle params) throws Exception {
		String result = null;
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
		if (ProxyTool.CURRENT_NET_TYPE != ProxyTool.ProxyNetType.NONE) {
			HttpHost proxy = new HttpHost(ProxyTool.CURRENT_NET_TYPE.getIp(), ProxyTool.CURRENT_NET_TYPE.getPort(), "http");
			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		}
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = null;
		BufferedReader br = null;
		try {
			String sendDataJson = parseParam2Json(command,params);
			L.i(TAG, sendDataJson);
			String preEncodeParam = Base64.encodeToString(sendDataJson.getBytes(), Base64.NO_CLOSE);
//			int i = encodeParam.indexOf("\n");
			String encodeParam = preEncodeParam.replaceAll("\n", "");
			String url = Config.API_URL+encodeParam;
			L.i(TAG, url);
			httpGet = new HttpGet(new URI(url));
			HttpResponse response = httpClient.execute(httpGet, localContext);
			InputStream is = response.getEntity().getContent();
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[512];
		    int rc = 0;   
		    while ((rc = is.read(buff, 0, 512))>0) {
		    	swapStream.write(buff, 0, rc);
		    }
			byte[] byteResult = Base64.decode(swapStream.toByteArray(), Base64.DEFAULT);
			if (null != byteResult) {
				result = new String(byteResult);
			}
			L.i(TAG, result);
			is.close();
			swapStream.close();
		} catch (ClientProtocolException e) {
			throw e;
		} catch (UnknownHostException e) {
			throw new LocalErrorException(Tips.ERROR_ON_HTTP_RESPONSE);
		} catch (IOException e) {
			throw e;
		} catch (RuntimeException ex) {
			if (null != httpGet) {
				httpGet.abort();
			}
			throw ex;
		} finally {
			try {
				if (null != br) {
					br.close();
				}
			} catch (IOException e) {
				throw e;
			}
		}
		// 返回为空，处理为参数解析错误
		if (StringUtils.isEmpty(result)) {
			throw new LocalErrorException(Tips.ERROR_ON_HTTP_RESPONSE);
		}
		JSONObject jobj = new JSONObject(result);
		if(StringUtils.isEmpty(jobj.getString("ReturnInfo"))){
			throw new LocalErrorException(jobj.getString("PromptInfo"));
		}
		return result;
	}
	
	public static String parseParam2Json(String command,Bundle params) {
		JSONObject jsonObject = new JSONObject();
		String generateSign = Md5.encode((command + Config.SIGN_PASSWORD));
		try {
			jsonObject.put("FunctionID", command);
			jsonObject.put("Sign", generateSign);
			for (String key : params.keySet()) {
				jsonObject.put(key, (null == params.get(key)) ? "" : params.get(key).toString());
			}
		} catch (JSONException e) {
			L.e(TAG, e.getMessage());
		}
		return jsonObject.toString();
	}
}
